﻿Imports System
Imports System.Collections.Generic
Imports VMWorkshop.Domain
Imports AutoMapper

Public Class WebFormsViewModel
    Private _products As IList(Of ProductListView) = Nothing
    Private _selectedProduct As ProductEditView = Nothing
    Private _repository As IProductRepository = Nothing
    Private _isPersistenceSuccessful As Boolean = False

    Public ReadOnly Property Products() As IList(Of ProductListView)
        Get
            If Me._products Is Nothing Then
                Dim p As IList(Of Product) = Me._repository.GetAll()
                Me._products = Mapper.Map(Of IList(Of Product), IList(Of ProductListView))(p)
            End If
            Return Me._products
        End Get
    End Property

    Public ReadOnly Property SelectedProduct() As ProductEditView
        Get
            Return Me._selectedProduct
        End Get
    End Property

    Public ReadOnly Property HasSelectedProduct() As Boolean
        Get
            Return Not String.IsNullOrEmpty(Me._selectedProduct.ProductId)
        End Get
    End Property

    Public ReadOnly Property IsPersistenceSuccessful() As Boolean
        Get
            Return Me._isPersistenceSuccessful
        End Get
    End Property

    Public Sub New(ByVal repository As IProductRepository)
        Me._repository = repository
        Me.ClearSelectedProduct()
    End Sub

    Public Sub GetSelectedProduct(ByVal productId As String)
        Dim id As Integer

        If Integer.TryParse(productId, id) Then
            Me.GetSelectedProduct(id)
        Else
            Throw New ArgumentException("The value for productId must be an integer.")
        End If

    End Sub

    Public Sub GetSelectedProduct(ByVal productId As Integer)
        Dim product As Product = Me._repository.GetProductById(productId)
        Me._selectedProduct = ProductEditView.ToProductEditView(product)
    End Sub

    Friend Sub PersistChanges(ByVal view As ProductEditView)
        Dim newProduct As Product = ProductEditView.ToProduct(view)
        Dim oldProduct As Product = Me._repository.GetProductById(view.ProductId)

        With oldProduct
            .Title = newProduct.Title
            .Description = newProduct.Description
            .QuantityOnHand = newProduct.QuantityOnHand
            .ReleaseDate = newProduct.ReleaseDate
            .Price = newProduct.Price
        End With

        Me._repository.Persist(oldProduct)
        Me._isPersistenceSuccessful = True
        Me.ClearSelectedProduct()
    End Sub

    Private Sub ClearSelectedProduct()
        Me._selectedProduct = New ProductEditView()
    End Sub
End Class